<?php
namespace Home\Controller;

class LoginController extends \Common\Controller\BaseController {
    private $_login;
    public function __construct()
    {
        parent::__construct();
        $this->_login = new \Home\Model\LoginModel();
    }

    public function login(){
        if(!empty($_POST)){
            $data['password'] = I('password');
            $data['name'] = I('name');
            $verify = I('verify');

            if($verify==null){
                $this->error('验证码不能为空！');
            }
            if($data['name']==null){
                $this->error('用户名不能为空！');
            }
            if($data['password']==null){
                $this->error('密码不能为空！');
            }


            $result = $this->_login->login($data,$verify);

            if($result == 1){
                session('username',$data['name']);
                $this->success("登录成功",'/index.php/'.MODULE_NAME."/Index/index");
            }else if($result == 2){
                $this->error("用户不存在",'/index.php/'.MODULE_NAME.'/Login/login');
            }else if($result == 3){
                $this->error("用户或密码不正确",'/index.php/'.MODULE_NAME.'/Login/login');
            }else{
                $this->error("验证码错误！",'/index.php/'.MODULE_NAME.'/Login/login');
            }
        }else{
            $this->display();
        }
    }

    function Verify(){
        $code = I('code');
        if($code){
            return $this->_login->Verify(null);
        }else{
            return $this->_login->Verify($code);
        }
    }

    public function logout(){
        session(null);
        $this->success("用户退出成功",U('Index/index'));
    }
    public function rigster(){
        if(!empty($_POST)){
            $data['password'] = I('password');
            $data['password2'] = I('password2');
            $data['name'] = I('name');
            $verify = I('verify');
            if($verify==null){
                $this->error('验证码不能为空！');
            }
            if($data['name']==null){
                $this->error('用户名不能为空！');
            }
            if($data['password']==null){
                $this->error('密码不能为空！');
            }
            if($data['password2']==null){
                $this->error('重复密码不能为空！');
            }

            $result = $this->_login->rigster($data,$verify);
            if($result == 1){
                $this->error("用户名已存在",U('Login/rigster'));
            }else{
                if($result == 3){
                    $this->error("密码不一致",U('Login/rigster'));
                }else if($result == 2){
                    $this->success("注册成功",U("Index/index"));
                }else{
                    $this->error('验证码错误！',U('Login/rigster'));
                }
            }
        }else{
            $this->display();
        }
    }
}